package com.xyht.sca_s.student_manage_system.modules.wx.util;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.xyht.sca_s.student_manage_system.common.util.CacheUtil;
import com.xyht.sca_s.student_manage_system.common.util.TimeUtil;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.wx.entity.WxMaPropertiesEntity;
import com.xyht.sca_s.student_manage_system.modules.wx.entity.WxMpPropertiesEntity;
import com.xyht.sca_s.student_manage_system.modules.wx.myEnum.MessageEventEnum;
import com.xyht.sca_s.student_manage_system.modules.wx.myEnum.MessageStepEnum;
import com.xyht.sca_s.student_manage_system.modules.wx.util.replyUtil.*;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.util.*;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.wx.constant.CommonConstant.BOOLEAN_FALSE;
import static com.xyht.sca_s.student_manage_system.modules.wx.myEnum.MessageEventEnum.*;
import static com.xyht.sca_s.student_manage_system.modules.wx.myEnum.MessageStepEnum.MESSAGE_STEP_ENUM_ALLOW_DENY;
import static com.xyht.sca_s.student_manage_system.modules.wx.myEnum.MessageStepEnum.MESSAGE_STEP_ENUM_ALLOW_PASS;

@Component
@Log4j2
public class WeChatUtil {
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WxMpPropertiesEntity wxMpPropertiesEntity;
    @Autowired
    private WxMaPropertiesEntity wxMaPropertiesEntity;
    @Autowired
    private CacheUtil cacheUtil;

    public WxMaJscode2SessionResult getSessionKey(WxMaService wxMaService,String code) throws Exception {
        WxMaJscode2SessionResult sessionResult = wxMaService.getUserService().getSessionInfo(code);
        return sessionResult;
    }

    public WxMpUser getWXMpOAuth2AccessToken(String code) throws Exception {
        WxOAuth2AccessToken result = wxMpService.getOAuth2Service().getAccessToken(code);
//        log.debug("openid+++++"+result.getOpenId());
//        log.debug("unionid+++++"+result.getUnionId());
        WxMpUser wxMpUser = wxMpService.getUserService().userInfo(result.getOpenId());
        return wxMpUser;
    }

    public boolean checkWXSign(HttpServletRequest request){
// 微信加密签名，需要使用本地计算出来的和这个对比，确认是微信发送的消息
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp"); // 时间戳
        String nonce = request.getParameter("nonce");       // 随机数
        String echostr = request.getParameter("echostr");  // 随机字符串
        // 将token、timestamp、nonce三个参数进行字典序排序
        List<String> list = new ArrayList<String>();
        list.add(wxMpPropertiesEntity.getToken());    // 公众号后台设置的token
        list.add(timestamp);
        list.add(nonce);
        Collections.sort(list);
        // 将三个参数字符串拼接成一个字符串进行sha1加密
        String tokenStr = "";
        for (int i = 0; i < list.size(); i++) {
            tokenStr += list.get(i);
        }
        String signatureStr = DigestUtils.sha1Hex(tokenStr);
        // 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        if (signature.equals(signatureStr)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     *
     * @param source_user_id  流程审批时为申请人id，待办处理和消息提醒时为目标用户id
     * @param target_user_id  流程审批时为申请人id，待办处理和消息提醒时为目标用户id
     * @param appName  应用类型
     * @param messageEventEnum  消息事件
     * @param messageStepEnum  消息步骤
     * @param content  消息自定义内容
     *
     *
     * */
    public void sendWXMPTemplateMessage(String source_user_id, //
                                        String target_user_id,
                                        String appName,
                                        MessageEventEnum messageEventEnum,
                                        MessageStepEnum messageStepEnum,
                                        String content){
        String message_description = "";
        String message_app = "";
        String message_event = "";
        String message_step = "";
        String message_content = "";
        String message_remark = "";
        String user_name = "";
        String open_id = "";
        String apply_username = "";
        try{
            if (!isNullOrEmpty(source_user_id)){
                SmsUser sourceUser = cacheUtil.getUserInfo(source_user_id);
                if (sourceUser == null){
                    return;
                }
                user_name = sourceUser.getRealName();
            }
            if (!isNullOrEmpty(target_user_id)){
                SmsUser targetUser = cacheUtil.getUserInfo(target_user_id);
                if (targetUser == null || targetUser.getIsMpBind() == BOOLEAN_FALSE || targetUser.getIsMessage() == BOOLEAN_FALSE){
                    return;
                }
                apply_username = targetUser.getRealName();
                open_id = targetUser.getWxMpId();
            }else {
                return;
            }
            message_description = "你好，"+
                    "你有一条新"+appName+","+messageStepEnum.getName();

            message_app = appName;
            message_event = messageEventEnum.getName();
            message_step = messageStepEnum.getName();
            if (messageEventEnum == MESSAGE_EVENT_ENUM_ALLOW){
                message_content = "【"+user_name+"】提交了一个申请";
                apply_username = user_name;
            }else if (messageEventEnum == MESSAGE_EVENT_ENUM_DEAL){
                message_content = "【"+user_name+"】发布了一个待办";
                apply_username = user_name;
            }else if (messageEventEnum == MESSAGE_EVENT_ENUM_COPY_MSG){
                message_content = "【"+user_name+"】抄送了你一条申请";
                apply_username = user_name;
            }else {
                if (messageStepEnum == MESSAGE_STEP_ENUM_ALLOW_PASS || messageStepEnum == MESSAGE_STEP_ENUM_ALLOW_DENY){
                    message_content = "你的申请已经"+messageStepEnum.getName()+"";
                }else{
                    message_content = content;
                }
            }


            WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();

            WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
            miniProgram.setUsePath(true);
            miniProgram.setAppid(wxMaPropertiesEntity.getAppId());
            miniProgram.setPagePath("");
            templateMessage.setMiniProgram(miniProgram);

            List<WxMpTemplateData> list = new ArrayList<>();
//            list.add(new WxMpTemplateData("first",message_description)); //流程描述
            list.add(new WxMpTemplateData("thing8",apply_username)); //申请人
            list.add(new WxMpTemplateData("thing7",message_app)); //流程名称
            list.add(new WxMpTemplateData("thing10", message_step)); //流程状态
            list.add(new WxMpTemplateData("time6", TimeUtil.DateHanZiSimpleFormat(new Date()))); //时间
            list.add(new WxMpTemplateData("thing9",message_content)); //审批类型
            templateMessage.setData(list);

            templateMessage.setTemplateId("clrILl9xoc-NDbRqPl7Y3ZbBbSbQI-anaKWcfxDs5lw");

            templateMessage.setToUser(open_id);

            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        }catch (Exception e){
            e.printStackTrace();
        }
    }



    // 还原4个字节的网络字节序
    int recoverNetworkBytesOrder(byte[] orderBytes) {
        int sourceNumber = 0;
        for (int i = 0; i < 4; i++) {
            sourceNumber <<= 8;
            sourceNumber |= orderBytes[i] & 0xff;
        }
        return sourceNumber;
    }

    // 随机生成16位字符串
    String getRandomStr() {
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 16; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    // 生成4个字节的网络字节序
    byte[] getNetworkBytesOrder(int sourceNumber) {
        byte[] orderBytes = new byte[4];
        orderBytes[3] = (byte) (sourceNumber & 0xFF);
        orderBytes[2] = (byte) (sourceNumber >> 8 & 0xFF);
        orderBytes[1] = (byte) (sourceNumber >> 16 & 0xFF);
        orderBytes[0] = (byte) (sourceNumber >> 24 & 0xFF);
        return orderBytes;
    }


    /**
     * 对明文进行加密.
     *
     * @param text 需要加密的明文
     * @return 加密后base64编码的字符串
     * @throws AesException aes加密失败
     */
    public String encrypt(String randomStr, String text) throws AesException {
        ByteGroup byteCollector = new ByteGroup();
        byte[] randomStrBytes = randomStr.getBytes(Charset.forName("utf-8"));
        byte[] textBytes = text.getBytes(Charset.forName("utf-8"));
        byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length);
        byte[] appidBytes = wxMpPropertiesEntity.getAppId().getBytes(Charset.forName("utf-8"));
        byte[] aesKey = Base64.decodeBase64(wxMpPropertiesEntity.getAes() + "=");
        // randomStr + networkBytesOrder + text + appid
        byteCollector.addBytes(randomStrBytes);
        byteCollector.addBytes(networkBytesOrder);
        byteCollector.addBytes(textBytes);
        byteCollector.addBytes(appidBytes);

        // ... + pad: 使用自定义的填充方式对明文进行补位填充
        byte[] padBytes = PKCS7Encoder.encode(byteCollector.size());
        byteCollector.addBytes(padBytes);

        // 获得最终的字节流, 未加密
        byte[] unencrypted = byteCollector.toBytes();

        try {
            // 设置加密模式为AES的CBC模式
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
            IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);

            // 加密
            byte[] encrypted = cipher.doFinal(unencrypted);
            Base64 base64 = new Base64();
            // 使用BASE64对加密后的字符串进行编码
            String base64Encrypted = base64.encodeToString(encrypted);

            return base64Encrypted;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.EncryptAESError);
        }
    }

    /**
     * 对密文进行解密.
     *
     * @param text 需要解密的密文
     * @return 解密得到的明文
     * @throws AesException aes解密失败
     */
    public String decrypt(String text) throws AesException {
        byte[] aesKey = Base64.decodeBase64(wxMpPropertiesEntity.getAes() + "=");

        byte[] original;
        try {
            // 设置解密模式为AES的CBC模式
            log.debug("开始解密++++++++："+text);
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES");
            IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
            cipher.init(Cipher.DECRYPT_MODE, key_spec, iv);

            // 使用BASE64对密文进行解码
            byte[] encrypted = Base64.decodeBase64(text);
            log.debug("解码++++++++"+ Arrays.toString(encrypted));

            // 解密
            original = cipher.doFinal(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.DecryptAESError);
        }

        String xmlContent, from_appid;
        try {
            // 去除补位字符
            byte[] bytes = PKCS7Encoder.decode(original);

            // 分离16位随机字符串,网络字节序和AppId
            byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);

            int xmlLength = recoverNetworkBytesOrder(networkOrder);

            xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), Charset.forName("utf-8"));
            from_appid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length),
                    Charset.forName("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.IllegalBuffer);
        }

        // appid不相同的情况
        if (!from_appid.equals(wxMpPropertiesEntity.getAppId())) {
            throw new AesException(AesException.ValidateAppidError);
        }
        return xmlContent;

    }

    /**
     * 将公众平台回复用户的消息加密打包.
     * <ol>
     * 	<li>对要发送的消息进行AES-CBC加密</li>
     * 	<li>生成安全签名</li>
     * 	<li>将消息密文和安全签名打包成xml格式</li>
     * </ol>
     *
     * @param replyMsg 公众平台待回复用户的消息，xml格式的字符串
     * @param timeStamp 时间戳，可以自己生成，也可以用URL参数的timestamp
     * @param nonce 随机串，可以自己生成，也可以用URL参数的nonce
     *
     * @return 加密后的可以直接回复用户的密文，包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串
     * @throws AesException 执行失败，请查看该异常的错误码和具体的错误信息
     */
    public String encryptMsg(String replyMsg, String timeStamp, String nonce) throws AesException {
        // 加密
        String encrypt = encrypt(getRandomStr(), replyMsg);

        // 生成安全签名
        if (timeStamp == "") {
            timeStamp = Long.toString(System.currentTimeMillis());
        }

        String signature = SHA1.getSHA1(wxMpPropertiesEntity.getToken(), timeStamp, nonce, encrypt);

        // System.out.println("发送给平台的签名是: " + signature[1].toString());
        // 生成发送的xml
        String result = XMLParse.generate(encrypt, signature, timeStamp, nonce);
        return result;
    }

    /**
     * 检验消息的真实性，并且获取解密后的明文.
     * <ol>
     * 	<li>利用收到的密文生成安全签名，进行签名验证</li>
     * 	<li>若验证通过，则提取xml中的加密消息</li>
     * 	<li>对消息进行解密</li>
     * </ol>
     *
     * @param msgSignature 签名串，对应URL参数的msg_signature
     * @param timeStamp 时间戳，对应URL参数的timestamp
     * @param nonce 随机串，对应URL参数的nonce
     * @param postData 密文，对应POST请求的数据
     *
     * @return 解密后的原文
     * @throws AesException 执行失败，请查看该异常的错误码和具体的错误信息
     */
    public String decryptMsg(String msgSignature, String timeStamp, String nonce, String postData)
            throws AesException {
        // 密钥，公众账号的app secret
        // 提取密文
        Object[] encrypt = XMLParse.extract(postData);

        // 解密
        String result = decrypt(encrypt[1].toString());
        return result;
    }

    /**
     * 验证URL
     * @param msgSignature 签名串，对应URL参数的msg_signature
     * @param timeStamp 时间戳，对应URL参数的timestamp
     * @param nonce 随机串，对应URL参数的nonce
     * @param echoStr 随机串，对应URL参数的echostr
     *
     * @return 解密之后的echostr
     * @throws AesException 执行失败，请查看该异常的错误码和具体的错误信息
     */
    public String verifyUrl(String msgSignature, String timeStamp, String nonce, String echoStr)
            throws AesException {
        String signature = SHA1.getSHA1(wxMpPropertiesEntity.getToken(), timeStamp, nonce, echoStr);

        if (!signature.equals(msgSignature)) {
            throw new AesException(AesException.ValidateSignatureError);
        }

        String result = decrypt(echoStr);
        return result;
    }


}
